<template>
  <div class="order-index">
    <el-card class="page-card">
      <div class="page-header">
        <h2>订单管理</h2>
        <el-button type="success" @click="showAddDialog" icon="Plus">新增订单</el-button>
      </div>

      <!-- 查询表单 -->
      <el-form :model="order" ref="formRef" label-width="120px" label-position="right" class="search-form">
          <el-row :gutter="20">
              <el-col :span="8">
                  <el-form-item label="订单号" prop="dingdan_num">
                      <el-input v-model="order.dingdan_num" placeholder="请输入订单号" clearable/>
                  </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-form-item label="订单状态" prop="state">
                      <el-select v-model="order.state" placeholder="请选择状态" clearable style="width: 100%">
                          <el-option label="全部" value="" />
                          <el-option label="待接单" value="0" />
                          <el-option label="商家未接单" value="1" />
                          <el-option label="商家已接单" value="2" />
                          <el-option label="骑手已接单" value="3" />
                          <el-option label="配送中" value="4" />
                          <el-option label="已完成" value="5" />
                      </el-select>
                  </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-form-item label="店铺ID" prop="shop_id">
                      <el-input v-model="order.shop_id" placeholder="请输入店铺ID" clearable/>
                  </el-form-item>
              </el-col>
          </el-row>

          <el-row :gutter="20">
              <el-col :span="24" style="text-align: center; margin-top: 5px;">
                  <el-space size="large">
                      <el-button type="primary" @click="doList" icon="Search">查询</el-button>
                      <el-button type="default" @click="resetForm(formRef)" icon="Refresh">重置</el-button>
                  </el-space>
              </el-col>
          </el-row>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" stripe hover-row border style="width: 100%" class="data-table">
        <el-table-column type="index" label="序号" width="80" align="center"/>
<!--        <el-table-column prop="id" label="ID" align="center"/>-->
        <el-table-column prop="dingdan_num" label="订单号" align="center"/>
        <el-table-column prop="shop_name" label="店铺名称" align="center"/>
<!--        <el-table-column prop="user_name" label="用户名称" align="center"/>-->
        <el-table-column prop="price" label="订单金额" align="center" sortable/>
        <el-table-column prop="state" label="订单状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.state == '0'" type="danger">待接单</el-tag>
            <el-tag v-else-if="scope.row.state == '1'" type="warning">商家未接单</el-tag>
            <el-tag v-else-if="scope.row.state == '2'" type="warning">商家已接单</el-tag>
            <el-tag v-else-if="scope.row.state == '3'" type="warning">骑手已接单</el-tag>
            <el-tag v-else-if="scope.row.state == '4'" type="warning">配送中</el-tag>
            <el-tag v-else-if="scope.row.state == '5'" type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="scope">
            <el-space size="small">
              <el-button type="primary" size="small" @click="showDetailPage(scope.row)" icon="View">详情</el-button>
              <el-button type="warning" size="small" @click="showUpdateDialog(scope.row)" icon="Edit">更新</el-button>
              <el-button type="danger" size="small" @click="doDelete(scope.row.id)" icon="Delete">删除</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

        <!-- 分页控件 -->
        <div class="pagination">
            <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 50]"
                    v-model:current-page="page.pageNum"
                    v-model:page-size="page.pageSize"
                    :total="page.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            />
        </div>

    </el-card>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增订单" width="50%" top="10vh" destroy-on-close>
      <add-page @flushPage="doFlushPage" @closeDialog="addDialogVisible = false"/>
    </el-dialog>

    <!-- 更新对话框 -->
    <el-dialog v-model="updateDialogVisible" title="更新订单" width="50%" top="10vh" destroy-on-close>
      <update-page ref="updatePageRef" @flushPage="doFlushPage" @closeDialog="updateDialogVisible = false"/>
    </el-dialog>

    <!-- 详情页面 -->
    <detail-page ref="detailPageRef"/>
  </div>
</template>

<style scoped>
.order-index {
  padding: 20px;
}

.page-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.search-form {
  padding: 0 20px 20px;
}

.data-table {
  margin: 0 20px 20px;
}

.pagination {
  margin: 0 20px 20px;
  text-align: right;
}
</style>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, FormInstance } from "element-plus";
import axios from 'axios'
import DetailPage from './DetailPage.vue';
import AddPage from './Addpage.vue';
import UpdatePage from './UpdatePage.vue';

// 表单查询数据对象
const order = ref({
    id: '',
    dingdan_num: '',
    shop_id: '',
    state: '',
    price: ''
});

const formRef = ref<FormInstance>();
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 表格数据
const tableData = ref([]);

// 分页相关变量
const page = ref({
    pageNum: 1,     // 当前页码
    pageSize: 5,   // 每页显示的记录数
    pages: 0,       // 总页数
    total: 0        // 总记录数
});

// 分页事件处理
const handleSizeChange = (val: number) => {
    page.value.pageSize = val;
    page.value.pageNum = 1;
    doList();
};

const handleCurrentChange = (val: number) => {
    page.value.pageNum = val;
    doList();
};

// 分页重置
const doPageReset = () => {
    page.value.pageNum = 1;
    page.value.pageSize = 5;
    page.value.pages = 0;
    page.value.total = 0;
}

// 对话框显示控制
const addDialogVisible = ref(false);
const updateDialogVisible = ref(false);
const updatePageRef = ref();
const detailPageRef = ref();


// 查询订单列表
const doList = async () => {
    try {
        const params = {
            ...order.value,
            pageNum: page.value.pageNum,
            pageSize: page.value.pageSize
        };

        const { data } = await axios.get('/api/dingdan', { params });
        console.log('API响应数据:', data);

        // 确保处理正确的分页数据结构
        if (data && data.list) {
            // 处理返回的分页数据，并确保数值字段是正确的类型
            tableData.value = (data.list || []).map(item => ({
                ...item,
                money: Number(item.money) || 0,
                gratuity: Number(item.gratuity) || 0
            }));
            
            // 从响应中获取分页信息，如果不存在则保持原有值
            page.value.total = data.total || page.value.total;
            page.value.pages = data.pages || page.value.pages;
        } else {
            // 如果数据结构不符合预期，给出提示并重置表格数据
            ElMessage.error('获取数据失败');
            tableData.value = [];
        }
    } catch (error) {
        console.error('请求失败:', error);
        ElMessage.error('请求失败，请检查网络连接');
        tableData.value = [];
    }
};
// 显示新增对话框
const showAddDialog = () => {
    addDialogVisible.value = true;
};

// 显示更新对话框
const showUpdateDialog = (row) => {
    updateDialogVisible.value = true;
    // 确保传递给更新页面的数据中数值字段是正确的类型
    const formattedRow = {
        ...row,
        money: Number(row.money) || 0,
        gratuity: Number(row.gratuity) || 0
    };
    updatePageRef.value.handleUpdateData(formattedRow);
};

// 显示详情页面
const showDetailPage = (row) => {
    // 确保传递给详情页面的数据中数值字段是正确的类型
    const formattedRow = {
        ...row,
        money: Number(row.money) || 0,
        gratuity: Number(row.gratuity) || 0
    };
    detailPageRef.value.handleDetailData(formattedRow);
};

// 删除订单
const doDelete = async (id) => {
    try {
        const { data } = await axios.delete(`/api/dingdan/${id}`);
        if (data > 0) {
            ElMessage.success('删除成功');
            doList();
        } else {
            ElMessage.error('删除失败');
        }
    } catch (error) {
        ElMessage.error('删除失败');
        console.error('删除失败:', error);
    }
};

// 刷新页面数据
const doFlushPage = () => {
    doList();
    doPageReset();
    resetForm;
};


// 页面加载时获取数据
onMounted(() => {
    doList();
});


</script>

